﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Leetcode_Array.Script.ListNode
{
    class ListNode
    {
        public int val;
        public ListNode next;
        public ListNode(int val = 0, ListNode next = null)
        {
            this.val = val;
            this.next = next;
        }
    }
    //=========================== 删除链表的倒数第n个节点
    //给你一个链表，删除链表的倒数第n个几点，并且返回链表的头结点
    //你能尝试使用一趟扫描实现吗
    
    class DeleteNode
    {
        public ListNode RemoveNthFromEnd(ListNode head, int n)
        {
            ListNode dummyHead = new ListNode(0);
            dummyHead.next = head;
            ListNode fast = dummyHead;
            ListNode slow = dummyHead;
            while(n-->0 && fast != null)
            {
                fast = fast.next;
            }
            fast = fast.next;//fast提前走一步，因为需要让slow指向删除及诶点的上一个节点
            while(fast != null)
            {
                fast = fast.next;
                slow = slow.next;
            }
            slow.next = slow.next.next;
            return dummyHead.next;
        }
    }
}
